package com.ww.yaodao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.ww.yaodao.config.AlipayConfig;
import com.ww.yaodao.convert.PayConvert;
import com.ww.yaodao.mapper.PayMapper;
import com.ww.yaodao.model.bo.PayDO;
import com.ww.yaodao.model.vo.pay.PayListRespVO;
import com.ww.yaodao.model.vo.pay.PayVO;
import com.ww.yaodao.service.PayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("payService")
@RequiredArgsConstructor
@Slf4j
public class PayServiceImpl implements PayService {
    /*    @Autowired
        private StringRedisTemplate redisTemplate;*/
    private final PayMapper payMapper;
    private final AlipayConfig aliPayConfig;
    private final PayConvert aliPayConvert;


    //签名方式
    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @Override
    public PayVO insertPayInfos(PayVO payVO, HttpServletResponse httpResponse, HttpServletRequest req) {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient =
                new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                        aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 异步回调
//        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
//        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();

        double totalAmount = payVO.getPayPrice();
        String traceNo = payVO.getTranceNo();
        String subject = payVO.getTitle();

        bizContent.set("out_trade_no", traceNo);  // 我们自己生成的订单编号
        bizContent.set("total_amount", totalAmount); // 订单的总金额
        bizContent.set("subject", subject);   // 支付的名称

        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置

        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        try {
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 支付请求完成将订单存入数据库中
        Date date = new Date();
        PayDO pays =
                PayDO.builder().date(date)
                        .payPrice(totalAmount)
                        .tranceNo(traceNo)
                        .title(subject).build();
        payMapper.insert(pays);
        return null;
    }

    @Override
    public PayListRespVO getCurrentInfo() {
        ArrayList<PayVO> payVOS = new ArrayList<>();
        int year = 0;
        int month = 0;
        int day = 0;

        PayDO payDO = payMapper.getCurrentInfo();
        // 订单时间
        Date date = payDO.getDate();
        // 系统时间
        Date date1 = new Date();
        int[] infoArr = this.getDate(date);
        infoArr[0]++;
        int[] sysArr = this.getDate(date1);

        year = (infoArr[0] > sysArr[0]) ? infoArr[0] - sysArr[0] : 0;
        if (infoArr[1] > sysArr[1]) {
            month = infoArr[1] - sysArr[1];
        } else {
            if (year > 0) {
                year--;
                month = infoArr[1] + 12 - sysArr[1];
            } else {
                month = 0;
            }
        }
        if (infoArr[2] > sysArr[2]) {
            day = infoArr[2] - sysArr[2];
        } else {
            if (month > 0) {
                month--;
                day = infoArr[2] + 31 - sysArr[2];
            } else {
                if (year > 0) {
                    year--;
                    month = 11;
                    day = infoArr[2] + 31 - sysArr[2];
                }
            }
        }


        PayVO payVO =
                PayVO.builder().payPrice(payDO.getPayPrice())
                        .title(payDO.getTitle()).tranceNo(payDO.getTranceNo())
                        .endYear(year).endMonth(month).endDay(day).build();
        payVOS.add(payVO);
        PayListRespVO payListRespVO =
                PayListRespVO.builder().payVOList(payVOS).build();

        return payListRespVO;
    }

    @Override
    public String notifyInfo(HttpServletRequest request) throws Exception {
        log.info("=========支付宝异步回调========");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
            log.info(name + " = " + request.getParameter(name));
        }


        // 支付宝验签
        if (Factory.Payment.Common().verifyNotify(params)) {
           /* // 验签通过
            log.info("交易名称: {}", params.get("subject"));
            log.info("交易状态:{} ", params.get("trade_status"));
            log.info("支付宝交易凭证号: {}", params.get("trade_no"));
            log.info("商户订单号: {}", params.get("out_trade_no"));
            log.info("交易金额:{} ", params.get("total_amount"));
            log.info("买家在支付宝唯一id: {}", params.get("buyer_id"));
            log.info("买家付款时间: {}", params.get("gmt_payment"));
            log.info("买家付款金额: {}", params.get("buyer_pay_amount"));
            auth_app_id
            */
            // 支付请求完成将订单存入数据库中
            log.info("价格：{}",params.get("total_amount"));
            log.info("标题:{}",params.get("subject"));
           /* Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            PayDO pays =
                    PayDO.builder().date(df.parse(params.get("timestamp")))
                            .payPrice(new Double(params.get("total_amount")))
                            .tranceNo(params.get("out_trade_no"))
                            .title(subject).build();
            payMapper.insert(pays);*/
        }

        return null;
    }


    public int[] getDate(Date date) {
        int[] intArr = new int[3];
        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        String[] split = format.split("-");
        // 计算得到截止日期
        intArr[0] = Integer.parseInt(split[0]);
        intArr[1] = Integer.parseInt(split[1]);
        intArr[2] = Integer.parseInt(split[2]);
        return intArr;
    }


}
